package net.sample.gismeteo.db;

import java.util.HashMap;

import net.sample.gismeteo.Common;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class ForecastProvider extends ContentProvider
{
	
	private static final String TAG = "ShowWeatherForecastProvider";

	private static final String DATABASE_NAME = "forecast.db";
	private static final int DATABASE_VERSION = 103;
	private static final String FORECAST_TABLE_NAME = "forecast";

	private static HashMap<String, String> sForecastProjectionMap;


	
	private static final int URI_FORECASTS= 1;	
	private static final int URI_FORECAST_TS = 2;

	private static final UriMatcher sUriMatcher;

	private static class DatabaseHelper extends SQLiteOpenHelper
	{



		DatabaseHelper(Context context)
		{
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL("CREATE TABLE " + FORECAST_TABLE_NAME + " ("
					+ Common.COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ Common.COL_TS + " INTEGER ,"
					+ Common.COL_BODY + " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + FORECAST_TABLE_NAME);
			onCreate(db);
		}
	}

	private DatabaseHelper mOpenHelper;


  static {
    sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    sUriMatcher.addURI(Common.AUTHORITY, "forecasts", URI_FORECASTS);
    sUriMatcher.addURI(Common.AUTHORITY, "forecasts/#", URI_FORECAST_TS);

    sForecastProjectionMap = new HashMap<String, String>();
    sForecastProjectionMap.put(Common.COL_ID, Common.COL_ID);
    sForecastProjectionMap.put(Common.COL_TS, Common.COL_TS);
    sForecastProjectionMap.put(Common.COL_BODY, Common.COL_BODY);
  }
  
	@Override
	public boolean onCreate()
	{
		mOpenHelper = new DatabaseHelper(getContext());
		return true;

	}

	@Override
	public Cursor query(Uri pUri, String[] pProjection, String pSelection, String[] pSelectionArgs, String pSortorder)
	{
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    switch (sUriMatcher.match(pUri)) {
    case URI_FORECASTS:
        qb.setTables(FORECAST_TABLE_NAME);
        qb.setProjectionMap(sForecastProjectionMap);
        break;

    case URI_FORECAST_TS:
        qb.setTables(FORECAST_TABLE_NAME);
        qb.setProjectionMap(sForecastProjectionMap);
        qb.appendWhere(Common.COL_ID + "=" + pUri.getPathSegments().get(1));
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + pUri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, pProjection, pSelection, pSelectionArgs, null, null, pSortorder);

    c.setNotificationUri(getContext().getContentResolver(), pUri);
    return c;
	}

	@Override
	public String getType(Uri pUri)
	{
    switch (sUriMatcher.match(pUri)) {
    case URI_FORECASTS:
        return Common.CONTENT_TYPE_WEATHER;

    case URI_FORECAST_TS:
        return Common.CONTENT_TYPE_FORECAST;

    default:
        throw new IllegalArgumentException("Unknown URI " + pUri);
    }
	}
	
	@Override
	public int delete(Uri pUri, String pSelection, String[] pArgs)
	{
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;
    switch (sUriMatcher.match(pUri)) {
    case URI_FORECASTS:
        count = db.delete(FORECAST_TABLE_NAME, pSelection, pArgs);
        break;

    case URI_FORECAST_TS:
        String lRowId = pUri.getPathSegments().get(1);
        count = db.delete(FORECAST_TABLE_NAME, Common.COL_ID + "=" + lRowId
                + (!TextUtils.isEmpty(pSelection) ? " AND (" + pSelection + ')' : ""), pArgs);
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + pUri);
    }

    getContext().getContentResolver().notifyChange(pUri, null);
    return count;
	}

	@Override
	public Uri insert(Uri pUri, ContentValues pContentValues)
	{
		if (sUriMatcher.match(pUri) != URI_FORECASTS)
		{
			throw new IllegalArgumentException("Unknown URI " + pUri);
		}

		// validation for pContentValues

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long lTS = db.insert(FORECAST_TABLE_NAME, "", pContentValues);
		if (lTS > 0)
		{
			Uri noteUri = ContentUris.withAppendedId(Common.CONTENT_URI, lTS);
			getContext().getContentResolver().notifyChange(noteUri, null);
			return noteUri;
		}

		throw new SQLException("Failed to insert row into " + pUri);
	}

	@Override
	public int update(Uri pUri, ContentValues pContentvalues, String pS, String[] pAs)
	{
		throw new SQLException("Update is not supported " + pUri);
	}
}
